Page({
  data: {
    equipment: {
      name: '',
      description: '',
      category: '',
      creditRequired: 60,
      imageUrl: '/assets/images/default-equipment.png',
      status: 1
    },
    isEdit: false,
    equipmentId: '',
    loading: false,
    submitting: false,
    categories: ['帐篷', '睡袋', '登山杖', '背包', '炊具', '灯具', '其他'],
    adminInfo: null
  },
  
  onLoad(options) {
    this.checkAdminLogin();
    
    if (options.id) {
      this.setData({
        isEdit: true,
        equipmentId: options.id
      });
      this.loadEquipmentDetail(options.id);
    }
  },
  
  // 检查管理员登录
  async checkAdminLogin() {
    const adminInfo = wx.getStorageSync('adminInfo');
    const adminToken = wx.getStorageSync('adminToken');
    
    if (!adminInfo || !adminToken) {
      this.redirectToLogin();
      return;
    }
    
    try {
      // 检查管理员身份是否有效
      const result = await wx.cloud.callFunction({
        name: 'checkAdminAuth',
        data: {
          adminId: adminInfo.adminId,
          token: adminToken
        }
      });
      
      const { code, data, message } = result.result;
      
      if (code === 0 && data) {
        // 验证通过，设置管理员信息
        this.setData({
          adminInfo: {
            ...adminInfo,
            ...data
          }
        });
      } else {
        // 验证失败，清除存储的信息并重定向到登录页
        wx.removeStorageSync('adminInfo');
        wx.removeStorageSync('adminToken');
        
        wx.showToast({
          title: message || '登录已过期，请重新登录',
          icon: 'none'
        });
        
        this.redirectToLogin();
      }
    } catch (error) {
      console.error('验证管理员身份错误', error);
      wx.showToast({
        title: '网络错误，请重试',
        icon: 'none'
      });
      this.redirectToLogin();
    }
  },
  
  // 加载装备详情
  async loadEquipmentDetail(id) {
    this.setData({ loading: true });
    
    try {
      const adminToken = wx.getStorageSync('adminToken');
      const result = await wx.cloud.callFunction({
        name: 'adminGetEquipmentDetail',
        data: {
          equipmentId: id,
          adminId: this.data.adminInfo.adminId,
          token: adminToken
        }
      });
      
      const { code, data, message } = result.result;
      
      if (code === 0 && data) {
        this.setData({
          equipment: data
        });
      } else {
        wx.showToast({
          title: message || '获取装备详情失败',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('获取装备详情失败', error);
      wx.showToast({
        title: '获取装备详情失败',
        icon: 'none'
      });
    } finally {
      this.setData({ loading: false });
    }
  },
  
  // 名称输入
  onNameInput(e) {
    this.setData({
      'equipment.name': e.detail.value
    });
  },
  
  // 描述输入
  onDescriptionInput(e) {
    this.setData({
      'equipment.description': e.detail.value
    });
  },
  
  // 信用分要求输入
  onCreditInput(e) {
    this.setData({
      'equipment.creditRequired': parseInt(e.detail.value, 10) || 60
    });
  },
  
  // 选择分类
  onCategoryChange(e) {
    this.setData({
      'equipment.category': this.data.categories[e.detail.value]
    });
  },
  
  // 选择状态
  onStatusChange(e) {
    this.setData({
      'equipment.status': e.detail.value ? 1 : 0
    });
  },
  
  // 选择图片
  chooseImage() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePath = res.tempFilePaths[0];
        
        this.setData({
          'equipment.imageUrl': tempFilePath,
          'equipment.tempImagePath': tempFilePath
        });
      }
    });
  },
  
  // 上传图片到云存储
  async uploadImage() {
    const { equipment } = this.data;
    
    if (!equipment.tempImagePath || equipment.tempImagePath.indexOf('cloud://') === 0) {
      return equipment.imageUrl;
    }
    
    try {
      const timestamp = Date.now();
      const cloudPath = `equipment/${timestamp}_${Math.floor(Math.random() * 10000)}.jpg`;
      
      const result = await wx.cloud.uploadFile({
        cloudPath,
        filePath: equipment.tempImagePath
      });
      
      return result.fileID;
    } catch (error) {
      console.error('上传图片失败', error);
      throw error;
    }
  },
  
  // 保存装备
  async saveEquipment() {
    const { equipment, isEdit, equipmentId } = this.data;
    
    // 验证表单
    if (!equipment.name.trim()) {
      wx.showToast({
        title: '请输入装备名称',
        icon: 'none'
      });
      return;
    }
    
    if (!equipment.category) {
      wx.showToast({
        title: '请选择装备分类',
        icon: 'none'
      });
      return;
    }
    
    this.setData({ submitting: true });
    
    try {
      // 上传图片
      let imageUrl = equipment.imageUrl;
      
      if (equipment.tempImagePath) {
        imageUrl = await this.uploadImage();
      }
      
      // 构建装备数据
      const equipmentData = {
        name: equipment.name,
        description: equipment.description,
        category: equipment.category,
        creditRequired: equipment.creditRequired,
        imageUrl: imageUrl,
        status: equipment.status
      };
      
      // 调用云函数保存装备
      const adminToken = wx.getStorageSync('adminToken');
      const result = await wx.cloud.callFunction({
        name: isEdit ? 'adminUpdateEquipment' : 'adminAddEquipment',
        data: {
          equipmentId: isEdit ? equipmentId : null,
          equipment: equipmentData,
          adminId: this.data.adminInfo.adminId,
          token: adminToken
        }
      });
      
      const { code, message } = result.result;
      
      if (code === 0) {
        wx.showToast({
          title: isEdit ? '更新成功' : '添加成功',
          icon: 'success'
        });
        
        // 返回上一页
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
      } else {
        wx.showToast({
          title: message || (isEdit ? '更新失败' : '添加失败'),
          icon: 'none'
        });
      }
    } catch (error) {
      console.error(isEdit ? '更新装备失败' : '添加装备失败', error);
      wx.showToast({
        title: isEdit ? '更新失败' : '添加失败',
        icon: 'none'
      });
    } finally {
      this.setData({ submitting: false });
    }
  },
  
  // 重定向到登录页
  redirectToLogin() {
    wx.redirectTo({
      url: '/pages/admin/login/login',
    });
  },
  
  // 返回上一页
  navigateBack() {
    wx.navigateBack();
  }
}) 